package com.java.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.java.bean.MenuInfo;
import com.java.bean.UserInfo;
import com.java.service.MenuService;
import com.java.service.UserService;
import com.java.util.Constants;
import com.java.util.MD5;
/**
 * 
 * 登录
 * 
 * @author
 * @version [版本号, 2016年1月15日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@RequestMapping("/sys")
public class LoginController {

    Logger log = LoggerFactory.getLogger(getClass());
    
    @Resource(name="userService")
    private UserService userService;

    @Resource(name="menuService")
    private MenuService menuService;
    
    /**
     * 
     * 跳转到登录页面
     * <功能详细描述>
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("toLogin")
    public String toLogin() {
	log.debug("跳转到登录页面");
	
	return "login";
    }
    
    /**
     * 
     * 用户登录
     * <功能详细描述>
     * @param username
     * @param password
     * @param req
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("login")
    public ModelAndView login(String username, String password, HttpServletRequest req) {
	ModelAndView mv = null;
	if (StringUtils.isNotEmpty(username)) {
	    UserInfo user = userService.selectUserByName(username);
	    if (null != user) {
		String md5 = MD5.GetMD5Code(password);
		if (md5.equals(user.getPwd())) {
		    req.getSession().setAttribute(Constants.USER_INFO, user);
		    mv = new ModelAndView("redirect:/tomain.do");
		} else {
		    Map<String, String> map = new HashMap<String, String>();
		    map.put("errMsg", "用户密码错误！");
		    mv = new ModelAndView("login", map);
		}
	    } else {
		Map<String, String> map = new HashMap<String, String>();
		map.put("errMsg", "用户不存在！");
		mv = new ModelAndView("login", map);
	    } 
	}
	return mv;
    }

    /**
     * 
     * 登录后跳转到主页面
     * <功能详细描述>
     * @param req
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("tomain")
    public ModelAndView tomain(HttpServletRequest req) { 
	UserInfo user = (UserInfo) req.getSession().getAttribute(Constants.USER_INFO);
	List<MenuInfo> list = menuService.selectMenusByUserId(user.getIid().toString());
	for (MenuInfo menuInfo : list) {
	    for (MenuInfo menu : list) {
		if (menu.getPid() == menuInfo.getIid()) {
		    menuInfo.getChildren().add(menu);
		}
	    }
	}
	return new ModelAndView("main");
    }
    
}
